Step 3: Vitest

Add vitest and fakerjs as a dev dependency:

yarn add -D vitest @faker-js/faker

So far, we have not tested our applications in a systematic way. It is time to correct that folly! To that aim, we will use Vitest, a “Vite-native” blazingly fast JavaScript Testing Framework.

Update the package.json file by adding “test” and “coverage” to the scripts:

 "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js",
    "test": "vitest",
    "coverage": "vitest run --coverage"
  },

Let’s write a simple test! Add a tests folder to the project root (outside of the src folder).

I recommend putting the test files in a tests  folder and replicating the server app's file structure and file names. Moreover, append the name of each test file with .test.js  for clarity.

As a convention, we store the test files in a tests folder replicating the src folder/file structure and file names.

Add a model subfolder to the tests folder. Next, add a test file Bookmark.test.js to the model subfolder with the following content:

import { expect, test } from "vitest";
import Bookmark from "../../src/model/Bookmark.js";
import { faker } from "@faker-js/faker";

test("test constructor", () => {
  const title = faker.lorem.sentence();
  const url = faker.internet.url();
  const bookmark = new Bookmark(title, url);
  expect(bookmark.title).toBe(title);
  expect(bookmark.url).toBe(url);
  expect(bookmark.id).toBeDefined();
});

To run the tests, open the terminal and run the command yarn test.

Untitled

Vitest will look for files with .test.js suffix and run them as tests.

Notice Vitest, by default, runs in the watch mode. You must press q to quit; while it runs, you can update the tests. Vitest will detect file changes and rerun the tests.

Notice furthermore, to write a test, we imported expect and test functions from vitest. The first argument to the test function is the test name; the second argument is a function that contains the expectations to test.

test("two plus two is four", () => {
  expect(2 + 2).toBe(4);
});

This syntax is compatible with other popular JavaScript testing frameworks such as Jest and Chai.

Aside: We wrote only one test! We should write more tests to consider cases where, e.g., the title and/or URL are invalid.

For now, let’s update the src/model/Bookmark.js by adding pre-conditions code contract:

import { v4 as uuidv4 } from "uuid";

class Bookmark {
  // pre: title is a non-empty string
  //      and url is a valid url
  constructor(title, url) {
    this.id = uuidv4();
    this.title = title;
    this.url = url;
  }
}

export default Bookmark;

Save and commit the changes.